package org.shangrila.app.sys.mb;

import java.io.Serializable;
import java.util.Date;

import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import org.shangrila.app.sys.eo.SysUser;
import org.shangrila.app.sys.shiro.AppEncryptService;
import org.shangrila.app.wechat.bean.WxError;
import org.shangrila.app.wechat.utils.WeChatUtil;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.IDHelper;
import org.shangrila.comm.utils.MsgsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
@SessionScoped
public class SysUserAddMB implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final transient Logger log = LoggerFactory.getLogger(SysUserAddMB.class);

	private String userno;
	private SysUser user;
	
	private DbAccess db = new DbAccess();
	
	public SysUserAddMB(){
		user = new SysUser();
	}
	   
	public String cancelAction(){
		return null;
	}	
	
	public String addAction(){		
		user.setSalt(AppEncryptService.encryptSalt(user.getUserno(),AppEncryptService.encryptMD5(user.getPassword())));
		user.setPassword(AppEncryptService.encryptPassword(user.getUserno(),AppEncryptService.encryptMD5(user.getPassword())));
		user.setType(0);
		user.setEnabled("0");  //初始插入0，邮箱验证后为1
		user.setId(IDHelper.genNumID());
		user.setCreatedTime(new Date());
		user.setWxno(user.getUserno()); //微信号和系统userno为同一个号
			
		db.beginTransaction();
		db.insert(user);
		db.commitTransaction();
		
		MsgsUtil.showMessages("新增用户", "新增用户成功。");
		
//微信新增用户
//		int d[] = {1};//部门，默认1，顶级，例{2,1}
//		WxError wxError = WeChatUtil.createUser(user.getWxno(),user.getUsername(),d,user.getPhone(),user.getEmail());
//		if(wxError.getErrcode()==0) {
//			log.info("新增用户-微信用户同步成功");
//		}else {
//			log.info("新增用户-微信用户同步失败-"+wxError.getErrmsg());
//		}
		
		user = new SysUser();
		return null;
	}

	
	public void validatePassword(FacesContext arg0, UIComponent arg1,
			Object arg3) throws ValidatorException {

		String content = (String) arg3;

		// 判断字符串的内容:字母数字下划线以及特殊字符(~`!@#$%^&*()+-_=|:;/'\"<>,.?)组合,3-36个字符。
		// 考虑SQL注入风险，不能使用' " = | + - <> []
		String regExp = "^[A-Za-z0-9~`!@#$%^&*()_<>/\\{}:;,.?]{3,20}$";
		// String regExp = "^[A-Za-z0-9]{3,16}$";
		if (!content.matches(regExp)) {
			throw new ValidatorException(MsgsUtil.showMessages("info",
					"请输入合法字符"));
		}
	}
	
	public SysUser getUser() {
		return user;
	}

	public void setUser(SysUser user) {
		this.user = user;
	}

	public String getUserno() {
		return userno;
	}


	public void setUserno(String userno) {
		this.userno = userno;
	}
   
}